package object_Test;

import java.util.Arrays;

import static kotlin.reflect.jvm.internal.impl.builtins.StandardNames.FqNames.comparable;

public class comparableTest {
    //接受Comparable数组的子类
    public static void sort(Comparable[] arr){
        for (int i = 0; i < arr.length-1; i++) {
            for (int j = 0; j < arr.length-1-i ; j++) {
                if (arr[j].compareTo(arr[j+1])>0){
                    //此时前一个大于后一个，交换
                    Comparable temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        Person[] per=new Person[]{
                new Person("小王",30),
                new Person("张三",18),
                new Person("李四",22)
        };
//        Arrays.sort(per);
        sort(per);
        System.out.println(Arrays.toString(per));
    }
}

class Person implements Comparable{
    String name;
    int age;


    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }


    @Override
    public int compareTo(Object o) {
        if (this==o){
            return 0;
        }
        if (o instanceof Person){
            //说明当前传入的o就是Person类型的引用，向下转型
            Person per=(Person) o;
            return this.age-per.age;
        }
        //此时的o必然不是Person类型的引用，就没法比，就抛出异常
        throw new IllegalArgumentException("不是person类型，无法比较");
    }
}
